<!--
 * @Author: ChaiHongJun
 * @Date: 2021-07-08 09:34:43
 * @LastEditors: ChaiHongJun
 * @LastEditTime: 2021-07-10 16:13:44
 * @version: 
 * @Description: 
-->
<template>
  <div class="login-container">
    <van-nav-bar
      class="app-nav-bar"
      title="登录/注册"
      left-arrow
      @click-left="$router.back()"
    />
    <!-- 登录表单 -->
    <van-cell-group>
      <van-form
        :show-error="false"
        :show-error-message="false"
        validate-first
        ref="login"
        @submit="login"
        @failed="onFailed"
      >
        <van-field
          v-model="user.mobile"
          name="mobile"
          clearable
          required
          icon-prefix="toutiao"
          left-icon="shouji"
          placeholder="请输入手机号"
          :rules="formRules.mobile"
        />
        <van-field
          v-model="user.code"
          clearable
          required
          icon-prefix="toutiao"
          left-icon="yanzhengma"
          placeholder="请输入验证码"
          :rules="formRules.code"
        >
          <template #button>
            <van-count-down
              :time="time"
              format="ss"
              v-if="CountDown"
              @finish="finish"
            />
            <van-button
              v-else
              size="mini"
              round
              class="send-btn"
              :loading="disabled"
              :loading-text="loadingText"
              loading-type="spinner"
              @click.prevent="sendSMS"
              >发送验证码</van-button
            >
          </template>
        </van-field>
        <div class="login-btn-wrap">
          <van-button
            type="info"
            block
            round
            class="login-btn"
            :disabled="disabled"
            >登录</van-button
          >
        </div>
      </van-form>
    </van-cell-group>
    <!-- /登录表单 -->
  </div>
</template>
<script>
import { login, getSMS } from "@/api/user.js";
import { Toast } from "vant";

export default {
  name: "Login",
  data() {
    return {
      user: {
        mobile: "", // 手机号
        code: "", // 验证码
      },
      disabled: false,
      loadingText: "稍后...",
      CountDown: false,
      time: 60 * 1000,
      formRules: {
        mobile: [
          { required: true, message: "输入手机号" },
          { validator: this.mobileValidator, message: "手机号格式不正确" },
        ],
        code: [
          { required: true, message: "输入验证码" },
          { validator: this.codeValidator, message: "验证码为6位纯数字" },
        ],
      },
    };
  },
  methods: {
    mobileValidator(phone) {
      //验证手机号格式
      return /^1[3456789]\d{9}$/.test(phone);
    },
    codeValidator(code) {
      //验证手机号格式
      return /^\d{6}$/.test(code);
    },
    // 验证码倒计时结束
    finish() {
      //还原发送验证码按钮
      this.CountDown = false;
    },
    onFailed(error) {
      // console.log("failed", error);
      let { errors } = error;
      if (errors[0]) {
        Toast.fail({
          duration: 3000,
          message: errors[0].message,
          position: top,
        });
      } else if (errors[1]) {
        Toast.fail({
          duration: 3000,
          message: errors[1].message,
          position: top,
        });
      }
    },
    /* 登录 */
    async login() {
      Toast.loading({
        duration: 0,
        message: "登录中...",
        forbidClick: true,
      });
      try {
        let { data, status } = await login(this.user);
        if (status == 201) {
          console.log(data);
          Toast.success("登录成功");
          let { token, refresh_token } = data.data;
          //token 和 refresh_token 存入 vuex 和本地localStorage
          console.log("token", token);
          console.log("refresh_token", refresh_token);
          this.$store.commit("user/SET_USER", { token, refresh_token });
          //跳转到首页
          this.$router.push({ path: "/", name: "Home" });
        } else if (status == 400) {
          Toast.fail("请求参数错误");
          console.log(data);
        } else if (status == 507) {
          Toast.fail("服务器数据库异常");
          console.log(data);
        }
      } catch (err) {
        Toast.fail("登录失败,手机号或验证码错误");
        console.log(err);
      }
    },
    /* 获取短信验证码 */
    async sendSMS() {
      try {
        // 1. 通过本地校验手机号
        await this.$refs.login.validate("mobile");
        // 2. 显示倒计时 并 隐藏登录按钮
        this.CountDown = true;
        this.disabled = true;
        // 3. 获得验证码
        let { data, status } = await getSMS(this.user.mobile);
        console.log("status:", status);
        console.log("mobile:", data);
        if (status == 200) {
          Toast.success({
            message: "验证码发送成功",
            position: top,
          });
        } else if (status == 404) {
          Toast.fail({
            message: "手机号码不存在",
            duration: 3000,
            position: top,
          });
        } else if (status == 429) {
          Toast.fail({
            message: "接口访问次数受限,每手机号每分钟1次",
            duration: 3000,
            position: top,
          });
        }
        //4. 显示登录按钮
        this.disabled = false;
      } catch (err) {
        //未知的错误
        Toast({
          message: err.message,
          duration: 3000,
          position: top,
        });
        console.log(err);
        this.disabled = false;
      }
    },
  },
  components: {},
};
</script>
<style lang="less" scoped>
.login-container {
  .send-btn {
    width: 76px;
    height: 23px;
    background-color: #ededed;
    .van-button__text {
      font-size: 11px;
      color: #666666;
    }
  }
  .login-btn-wrap {
    padding: 26px 16px;
    .login-btn {
      background-color: #6db4fb;
      border: none;
      .van-button__text {
        font-size: 16px;
      }
    }
  }
}
</style>
